package intelligentCustomer.reasoning;

import dev.langchain4j.model.chat.ChatLanguageModel;
import dev.langchain4j.model.input.Prompt;
import dev.langchain4j.model.input.PromptTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * 验证步骤
 * 验证生成的解决方案是否满足用户需求
 */
public class ValidationStep implements ReasoningStep {
    /** 大语言模型 */
    private final ChatLanguageModel model;
    
    /** 提示模板 */
    private static final PromptTemplate PROMPT_TEMPLATE = PromptTemplate.from(
        "验证以下解决方案是否满足用户需求。\n" +
        "用户查询: {{query}}\n" +
        "识别的需求: {{needs}}\n" +
        "生成的解决方案: {{solution}}\n\n" +
        "请评估解决方案的质量，包括:\n" +
        "1. 需求满足度 (0-100)\n" +
        "2. 解决方案的优点\n" +
        "3. 解决方案的缺点\n" +
        "4. 改进建议\n\n" +
        "以JSON格式返回结果，包含以上四个字段。"
    );
    
    /**
     * 构造函数
     * 
     * @param model 大语言模型
     */
    public ValidationStep(ChatLanguageModel model) {
        this.model = model;
    }
    
    /**
     * 执行验证步骤
     * 
     * @param context 推理上下文
     */
    @Override
    public void execute(ReasoningContext context) {
        try {
            // 获取需求识别和解决方案结果
            String needs = (String) context.getAttribute("needsIdentification");
            String solution = context.getSolution();
            
            if (needs == null || solution == null) {
                context.setSuccessful(false);
                context.addReasoningStep(getName(), "无法获取需求或解决方案");
                return;
            }
            
            // 准备提示参数
            Map<String, Object> variables = new HashMap<>();
            variables.put("query", context.getQuery());
            variables.put("needs", needs);
            variables.put("solution", solution);
            
            // 生成提示
            Prompt prompt = PROMPT_TEMPLATE.apply(variables);
            
            // 调用模型进行验证
            String validation = model.generate(prompt.text());
            
            // 将验证结果添加到推理链
            context.addReasoningStep(getName(), validation);
            
            // 将验证结果存储到上下文
            context.setAttribute("validation", validation);
            
            // 解析满足度并更新置信度
            // 实际应用中应该使用JSON解析库
            double satisfactionScore = extractSatisfactionScore(validation);
            context.setConfidence(satisfactionScore / 100.0);
            
            // 如果满足度过低，标记推理失败
            if (satisfactionScore < 60) {
                context.setSuccessful(false);
                context.addReasoningStep(getName(), "解决方案满足度过低: " + satisfactionScore);
            }
        } catch (Exception e) {
            context.setSuccessful(false);
            context.addReasoningStep(getName(), "验证失败: " + e.getMessage());
        }
    }
    
    /**
     * 从验证结果中提取满足度分数
     * 
     * @param validation 验证结果
     * @return 满足度分数
     */
    private double extractSatisfactionScore(String validation) {
        // 简化实现，实际应使用JSON解析
        try {
            if (validation.contains("\"需求满足度\":")) {
                int start = validation.indexOf("\"需求满足度\":") + "\"需求满足度\":".length();
                int end = validation.indexOf(",", start);
                if (end == -1) end = validation.indexOf("}", start);
                String scoreStr = validation.substring(start, end).trim();
                return Double.parseDouble(scoreStr);
            }
        } catch (Exception e) {
            // 解析失败，返回默认值
        }
        return 70.0; // 默认满足度
    }
    
    /**
     * 获取步骤名称
     * 
     * @return 步骤名称
     */
    @Override
    public String getName() {
        return "验证";
    }
} 